package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrDao attrDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存属性
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttr(AttrVo attr) {
        //创建一个属性对象
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        // 等于1 说明基本属性 才进行保存分组关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            //属性-分组-中间关系表的对象,来维持属性和属性之间关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(relationEntity);
        }
    }
    /**
     * 规格参数,销售属性列表,这个方法是公用的
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, long catelogId, String attrType) {
        //根据属性类型来进行查询
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?
                                                                            ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():
                                                                            ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId != 0){
            wrapper.eq("catelog_id",catelogId);
        }
        String key =(String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((wrapper01)->{
                wrapper01.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //拿到分页数据
        List<AttrEntity> records = page.getRecords();
        //查询的属性中没有分类名称和分组属性名称
        List<AttrRespVo> respVo = records.stream().map(attrEntity -> {
            //设置分类和分组的名称
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            Long catId = attrEntity.getCatelogId();
            CategoryEntity categoryEntity = categoryService.getById(catId);
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            //销售属性是没有分组的
            if("base".equalsIgnoreCase(attrType)){
                //设置分组的名称
                Long attrId = attrEntity.getAttrId();
                //因为属性表没有分组id，只能先去属性分组关系表先把分组id查出来,再去查分组名
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                if (relationEntity != null) {
                    //拿到属性分组的id
                    Long attrGroupId = relationEntity.getAttrGroupId();
                    if(attrGroupId!=null){
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVo);
        return pageUtils;
    }
    /**
     * 属性回显
     */
    @Override
    public AttrVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = attrDao.selectById(attrId);
        AttrVo attrVo = new AttrVo();
        if(attrEntity!=null){
            BeanUtils.copyProperties(attrEntity,attrVo);
            Long catelogId = attrEntity.getCatelogId();
            Long[] path = categoryService.findCatelogPath(catelogId);
            //设置三级分类
            attrVo.setCatelogPath(path);
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if(relationEntity!=null){
                //来回显分组名称的
                attrVo.setAttrGroupId(relationEntity.getAttrGroupId());
            }
        }
        return attrVo;
    }
    /**
     * 修改商品属性
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        //先更新一下属性表
        this.updateById(attrEntity);
        Long attrId = attrEntity.getAttrId();
        Long attrGroupId = attrVo.getAttrGroupId();
        //根据 attr_id 是否可以查询到结果
        Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attrGroupId);
        relationEntity.setAttrId(attrId);
        //如果没有,就直接保存
        if(count>0){
            relationDao.update(relationEntity,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrId));
        }else{
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = entities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        List<AttrEntity> attrEntities = null;
        if(attrIds!=null&&!attrIds.isEmpty()){
            attrEntities = attrDao.selectBatchIds(attrIds);
        }
        return attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] relationVo) {
        if(relationVo!=null&&relationVo.length>0){
            //转成一个集合
            List<AttrGroupRelationVo> relationVoList = Arrays.asList(relationVo);
            List<AttrAttrgroupRelationEntity> relationList = relationVoList.stream().map(attrGroupRelationVo -> {
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                BeanUtils.copyProperties(attrGroupRelationVo, relationEntity);
                return relationEntity;
            }).collect(Collectors.toList());
            relationDao.deleteBatchRelation(relationList);
        }
    }
   /**
    * 获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
    */
//    @Override
//    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
//        //当前分组只能关联自己分类下的属性
//        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
//        //拿到分类id
//        Long catId = attrGroupEntity.getCatelogId();
//        //拿到没有关联的属性id
//        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().ne("attr_group_id", attrgroupId));
//        List<Long> attrIds = null;
//        if(entities!=null&&!entities.isEmpty()){
//            attrIds = entities.stream().map(item -> {
//                return item.getAttrId();
//            }).collect(Collectors.toList());
//        }
//        //2.3 从当前分类的所有属性中移除这些属性
//        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
//                .eq("catelog_id", catId)
//                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
//        if(attrIds!=null&&!attrIds.isEmpty()){
//            // 在attrids 数组中得id不用进行查询
//            wrapper.in("attr_id", attrIds);
//        }
//        //取出参数进行 对应条件查询
//        String key = (String) params.get("key");
//        if (!StringUtils.isEmpty(key)) {
//            wrapper.and((w) -> {
//                w.eq("attr_id", key).or().like("attr_name", key);
//            });
//        }
//        // 根据分页数据 以及 wrapper进行查询
//        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
//        PageUtils pageUtils = new PageUtils(page);
//        return pageUtils;
//    }

   @Override
   public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
       // 1、当前分组只能关联自己所属分类里面的所有属性
       AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
       Long catelogId = attrGroupEntity.getCatelogId();

       //2、当前分组只能关联别的分组没有引用的属性
       //2.1 当前分类下的 **其他分组** 根据分类id进行查询
       List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
               .eq("catelog_id", catelogId));
       // 拿到分组id
       List<Long> collect = group.stream().map(item -> {
           return item.getAttrGroupId();
       }).collect(Collectors.toList());

       //2.2 这些分组关联的属性  根据分组id查询出关联表
       List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
               .in("attr_group_id", collect));
       // 拿到所有的属性id
       List<Long> attrIds = groupId.stream().map((item) -> {
           return item.getAttrId();
       }).collect(Collectors.toList());

       //2.3 从当前分类的所有属性中移除这些属性
       QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
               .eq("catelog_id", catelogId)
               .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

       // attrIds 属性id数组不为空
       if (attrIds != null && attrIds.size() > 0) {
           // 在attrids 数组中得id不用进行查询
           wrapper.notIn("attr_id", attrIds);
       }
       //取出参数进行 对应条件查询
       String key = (String) params.get("key");
       if (!StringUtils.isEmpty(key)) {
           wrapper.and((w) -> {
               w.eq("attr_id", key).or().like("attr_name", key);
           });
       }
       // 根据分页数据 以及 wrapper进行查询
       IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
       PageUtils pageUtils = new PageUtils(page);
       return pageUtils;
   }



}